﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Text;
using System.Windows;
using System.Xml.Linq;
using EbbinghausWord.Entities;
using System.Linq;

namespace EbbinghausWord.BLL
{
    /// <summary>
    /// 单词学习管理
    /// </summary>
    public static class WordBookManager
    {
        #region private field
        private static List<WordEntity> _wordbook = null;
        //private static Queue<WordEntity> _queue = new Queue<WordEntity>();


        #endregion

        #region public method

        /// <summary>
        /// 初始化单词本
        /// </summary>
        public static void InitWordbook()
        {
            if (IsExistUserWorkbook())
            {
                OpenUserWorkbook();
            }
            else
            {
                CreateUserWorkbook();
            }
        }

        /// <summary>
        /// 获得第一个单词
        /// </summary>
        /// <returns></returns>
        public static WordEntity GetFirstWord()
        {
            //if (_queue.Count > 0) _queue = new Queue<WordEntity>();
            //WordQueueManager.InitQueue();

            if (IsHaveWordInWordBook())
            {
                //从单词本中获得需要复习的单词加入到队列中
                GetReviewWordBookWithoutQueue().AddToQueue();
            }
            else
            {
                //词典中是否还有未学习的单词
                WordBook.Where(x => !x.IsInTheWordBook && !WordQueueManager.Contains(x))
                    .ToList().AddToQueue(SystemConfig.InitWordCount);
            }

            return WordQueueManager.Peek();
        }

        /// <summary>
        /// 获得下一个单词
        /// </summary>
        /// <returns></returns>
        public static WordEntity GetNextWord()
        {
            //当前队列是否小于20
            if (WordQueueManager.Count < SystemConfig.MinQueueWordCount)
            {
                //单词本中是否有当前需要记忆的单词
                if (IsHaveWordInWordBook())
                {
                    //将单词本中需要复习的单词 加入到队列中
                    GetReviewWordBookWithoutQueue().AddToQueue(SystemConfig.IncreaseQueueWordCount);
                }
                else
                {
                    //从字典中加载20个新单词（不在用户词典、不在队列中），不足20加载最大数量
                    WordBook.Where(x => !x.IsInTheWordBook && !WordQueueManager.Contains(x))
                                       .ToList().AddToQueue(SystemConfig.IncreaseQueueWordCount);
                }
            }

            //队列中是否还有单词
            return WordQueueManager.Peek();
        }

        /// <summary>
        /// 清除用户学习记录
        /// </summary>
        public static void ClearWorkbook()
        {
            StoreManager.DeleteFile(SystemConfig.UserWordkBookFileName);
            //清除队列
            //_queue.Clear();
            WordQueueManager.InitQueue();

            //初始化用户单词本
            InitWordbook();
            IsNeedReflesh = true;
        }

        /// <summary>
        /// 记住单词
        /// </summary>
        /// <param name="wordEntity"></param>
        public static WordEntity RememberWord()
        {
            //当前单词出队
            var wordEntity = WordQueueManager.Dequeue();

            //当前单词是否在单词本中
            if (wordEntity.IsInTheWordBook)
            {
                //修改单词的记忆级别
                ReviewManager.SetWordRemeberLevel(wordEntity);
            }
            else
            {

                //是否第3次记住
                if (++wordEntity.RememberTimes < 3)
                {
                    WordQueueManager.Enqueue(wordEntity, wordEntity.RememberTimes + 2);
                }
                else
                {
                    //加入到单词本
                    ReviewManager.AddToWordbook(wordEntity);
                }
            }

            //当前单词 “记住” 计数器 加1
            wordEntity.RememberCounter++;
            return WordBookManager.GetNextWord();
        }

        /// <summary>
        /// 没记住单词
        /// </summary>
        /// <returns></returns>
        public static WordEntity RorgetWord()
        {
            //当前单词出队
            var wordEntity = WordQueueManager.Dequeue();
            //设置记忆次数为0
            wordEntity.RememberTimes = 0;
            //设置记忆等级为0
            wordEntity.RememberLevel = 0;
            //从单词本移除
            wordEntity.IsInTheWordBook = false;
            wordEntity.NotRememberCounter++;
            //当前单词重新入队，排队队列的第2位
            WordQueueManager.Enqueue(wordEntity, 2);

            return WordBookManager.GetNextWord();
        }

        /// <summary>
        /// 彻底记住当前单词
        /// </summary>
        public static WordEntity CompleteRemeberWord()
        {
            //当前单词出队
            var wordEntity = WordQueueManager.Dequeue();

            //加入到单词本
            if (!wordEntity.IsInTheWordBook)
            {
                wordEntity.IsInTheWordBook = true;
                wordEntity.StartRemeberingDateTime = DateTime.Now;
            }

            //设置记忆等级为8，彻底记住
            wordEntity.RememberLevel = SystemConfig.AchievementRememberLevel;

            //当前单词 “记住” 计数器 加1
            wordEntity.RememberCounter++;

            return WordBookManager.GetNextWord();
        }

        /// <summary>
        /// 获得所有记住的单词
        /// </summary>
        /// <returns></returns>
        public static List<WordEntity> GetAchievementWords()
        {
            return _wordbook.Where(x => x.RememberLevel == SystemConfig.AchievementRememberLevel).ToList();
        }

        /// <summary>
        /// 获得学习中的单词列表，其中不包括 不在单词本 和 已经记住的单词
        /// </summary>
        /// <returns></returns>
        public static List<WordEntity> GetLearningWords()
        {
            return _wordbook.Where(x => x.IsInTheWordBook
                && x.RememberLevel != SystemConfig.AchievementRememberLevel)
                .OrderByDescending(x => x.RememberLevel).ToList();
        }

        /// <summary>
        /// 获得单词本中单词，包括学习中 和 已经记住的单词
        /// </summary>
        /// <returns></returns>
        public static List<WordEntity> GetWordsInWordbook()
        {
            return _wordbook.Where(x => x.IsInTheWordBook).ToList();
        }

        /// <summary>
        /// 根据英文获得单词实体
        /// </summary>
        /// <param name="english"></param>
        /// <returns></returns>
        public static WordEntity GetWordByEnglish(string english)
        {
            return WordBook.First(x => x.English == english);
        }

        /// <summary>
        /// 顺序排列单词本
        /// </summary>
        public static void OrderWordBook()
        {
            _wordbook = _wordbook.OrderBy(x => x.English).ToList();
        }

        /// <summary>
        /// 乱序排列单词本
        /// </summary>
        public static void UnorderWordBook()
        {
            _wordbook = _wordbook.OrderBy(x => x.OrderRandom).ToList();
        }

        /// <summary>
        /// 获得队列中没有的 待复习单词
        /// </summary>
        /// <returns></returns>
        private static List<WordEntity> GetReviewWordBookWithoutQueue()
        {
            return ReviewManager.GetReviewWordBook().Where(x => !WordQueueManager.Contains(x))
                .OrderBy(x => x.RememberLevel).ToList();
        }

        #endregion

        #region public property

        /// <summary>
        /// 用户单词本
        /// </summary>
        public static List<WordEntity> WordBook
        {
            get
            {
                if (_wordbook == null)
                    InitWordbook();
                return _wordbook;
            }
            set { _wordbook = value; }
        }

        /// <summary>
        /// 是否从备份中恢复
        /// </summary>
        public static bool IsNeedReflesh { get; set; }

        #endregion

        #region private method

        /// <summary>
        /// 单词本中是否还有未复习（达到了复习时间，不在队列中）的单词
        /// </summary>
        private static bool IsHaveWordInWordBook()
        {
            return GetReviewWordBookWithoutQueue().Count != 0;
        }

        /// <summary>
        /// 创建用户单词本
        /// </summary>
        private static void CreateUserWorkbook()
        {
            //初始化个人单词本
            BuildUserWorkbook();

            //单词本存入到存储中
            StoreManager.SaveUserWordbook();
        }

        /// <summary>
        /// 用户单词本是否存在
        /// </summary>
        private static bool IsExistUserWorkbook()
        {
            return StoreManager.IsFileExist(SystemConfig.UserWordkBookFileName);
        }

        /// <summary>
        /// 打开用户单词本
        /// </summary>
        private static void OpenUserWorkbook()
        {
            _wordbook = StoreManager.OpenFile(SystemConfig.UserWordkBookFileName);
        }

        /// <summary>
        /// 初始化个人单词本
        /// </summary>
        private static void BuildUserWorkbook()
        {
            _wordbook = DictionaryManager.GetWordDictionary().Values
                .Select(x => new WordEntity()
                {
                    English = x.English,
                    Chinese = x.Chinese,
                    Soundmark = x.Soundmark,
                    IsInTheWordBook = false,
                    RememberStatus = RememberStatus.NotRemember,
                }
            ).ToList();
        }


        #endregion

    }
}
